package com.snake.vargoappstore.loader;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;

import com.snake.mylibrary.loader.DynamicLoader;
import com.snake.mylibrary.loader.DynamicResult;
import com.snake.mylibrary.net.HttpStatus;
import com.snake.mylibrary.utils.ApkUtils;
import com.snake.vargoappstore.db.LocalAppInfo;
import com.snake.vargoappstore.result.ManagerFragmentLeftResult;

import java.util.ArrayList;
import java.util.List;


public class ManagerFragmentLeftLoader extends DynamicLoader {

    private Context mContext;
    public ManagerFragmentLeftLoader(Context context) {
        super(context);
        mContext = context;
    }

    @Override
    protected DynamicResult createDynamicResult() {
        PackageManager pm = mContext.getPackageManager();
        List<PackageInfo> packages = pm.getInstalledPackages(0);
        List<LocalAppInfo>  localAppInfos = new ArrayList<>();
        for (PackageInfo packageInfo:packages){
            String packageName = packageInfo.packageName;
            int versionCode = packageInfo.versionCode;
            String versionName = packageInfo.versionName;
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;
            if (ApkUtils.isThirdApp(applicationInfo)) {
                Drawable icon = applicationInfo.loadIcon(pm);
                CharSequence label = applicationInfo.loadLabel(pm);
                int flags = applicationInfo.flags;
                LocalAppInfo localAppInfo = new LocalAppInfo(icon, label, packageName, versionCode, versionName,flags);
                localAppInfos.add(localAppInfo);
            }
        }
        ManagerFragmentLeftResult managerFragmentLeftResult = new ManagerFragmentLeftResult(null, HttpStatus.HTTP_OK);
        managerFragmentLeftResult.setLocalAppInfos(localAppInfos.toArray(new LocalAppInfo[0]));
        return managerFragmentLeftResult;
    }
}
